package com.team.mp.api.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team.mp.api.bo.ResidentSignListBo;
import com.team.mp.api.bo.SignBo;
import com.team.mp.api.bo.SignRecordSearchBo;
import com.team.mp.api.service.intf.SignRecordService;
import com.team.mp.mapper.dao.*;
import com.team.mp.mapper.dto.ResidentSignDto;
import com.team.mp.mapper.dto.SignRecordDetailDto;
import com.team.mp.mapper.dto.SignRecordSearchDto;
import com.team.mp.mapper.entity.Label;
import com.team.mp.mapper.entity.ResidentTag;
import com.team.mp.mapper.entity.SignRecord;
import com.team.mp.vo.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import java.io.IOException;

/**
 * 千锋郑州Java学科欢迎你
 *
 * @program: Tproject
 * @description: 业务接口实现层
 * @author: lx
 * @create: 2023-03-27 16:44:59
 */
@Service
public class SignRecordServiceImpl implements SignRecordService {
    /**
     * 注入持久层对象
     */
    @Resource
    private SignRecordDao dao;
    @Resource
    private ResidentDetailDao residentDao;
    @Resource
    private ServicePackDao servicePackDao;

    @Resource
    private ResidentTagDao residentTagDao;
    @Resource
    private LabelDao labelDao;

    /**
     * 新增内容
     */
    @Override
    public R save(SignRecord signRecord) {
        if (signRecord != null) {
            int i = dao.insert(signRecord);
            if (i > 0) {
                return R.ok();
            }
        }
        return R.fail("亲，新增异常！");
    }

    /**
     * 修改内容
     */
    @Override
    public R update(SignRecord signRecord) {
        if (signRecord != null) {
            int i = dao.updateById(signRecord);
            if (i > 0) {
                return R.ok();
            }
        }
        return R.fail("亲，修改异常！");
    }

    @Override
    public R pass(Integer id) {
        SignRecord signRecord = new SignRecord();
        signRecord.setId(id);
        signRecord.setState(3);
        int i = dao.updateById(signRecord);
        if (i > 0) {
            return R.ok();
        }
        return R.fail("亲，审核异常！");
    }

    @Override
    public R reject(Integer id) {
        SignRecord signRecord = new SignRecord();
        signRecord.setId(id);
        signRecord.setState(2);
        int i = dao.updateById(signRecord);
        if (i > 0) {
            return R.ok();
        }
        return R.fail("亲，审核异常！");
    }

    /**
     * 删除
     */
    @Override
    public R del(long id) {
        if (id > 0) {
            int i = dao.deleteById(id);
            if (i > 0) {
                return R.ok();
            }
        }
        return R.fail("删除异常");
    }

    /**
     * 查询详情
     */
    @Override
    public R queryById(long id) {
        SignRecordDetailDto dto = new SignRecordDetailDto();
        SignRecord signRecord = dao.selectById(id);
        BeanUtils.copyProperties(signRecord, dto);
        Integer residentId = signRecord.getResidentId();
        dto.setResident(residentDao.selectById(residentId));
        dto.setPack(servicePackDao.selectById(signRecord.getPid()));

        List<ResidentTag> rid = residentTagDao.selectList(new QueryWrapper<ResidentTag>().eq("rid", residentId));
        for (int i = 0; i < rid.size(); i++) {
            Label label = labelDao.selectOne(new QueryWrapper<Label>().eq("id", rid.get(i).getTagid()));
            dto.getLabel().add(label);
        }

        return R.ok(dto);
    }

    /**
     * 查询详情
     */
    @Override
    public R queryById1(long id) {

        return R.ok(dao.queryById(id));
    }

    /**
     * 查询 所有数据
     */
    @Override
    public R queryAll() {
        return R.ok(dao.selectList(null));
    }

    /*条件查询*/
    @Override
    public R queryByCond(int page, int size, SignRecordSearchBo bo) {
        return R.ok(dao.selectInfo(new Page<>(page, size), bo.getDepartmentId(),
                bo.getTeamId(),
                bo.getSerpackId(),
                bo.getSignStatus(),
                bo.getCtime()));
    }

    @Override
    public R output(HttpServletResponse response) {
        //1.设置下载的响应消息头
        response.setHeader("Content-Disposition", "attachment;filename=user_" + System.currentTimeMillis() + ".xlsx");
        //2.查询数据
        List<SignRecordSearchDto> list = dao.selectInfo(new Page<>(), null, null, null, null, null).getRecords();
        //3.生成Excel 同时写出
        try {
            EasyExcel.write(response.getOutputStream(), SignRecordSearchDto.class).sheet("自动导出").doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @Override
    public R before(int id) {
        SignBo signBo = new SignBo();
        QueryWrapper<SignRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resident_id", id);
        List<SignRecord> signRecords = dao.selectList(queryWrapper);
        if (signRecords != null && signRecords.size() > 0) {
            signBo.setType(2); // 设置类型为续约
        } else {
            signBo.setType(1); // 设置类型为首次签约
        }
        // 创建wapper，查询最大的id
        QueryWrapper<SignRecord> wrapper = new QueryWrapper<>();
        wrapper.select("max(id) as id");
        SignRecord signRecord = dao.selectOne(wrapper);
        if (signRecord != null) {
            signBo.setId(signRecord.getId() + 1); // 设置签约编号
        }
        signBo.setState(1); // 设置签约状态
        signBo.setApplyTime(new Date()); // 设置申请时间
        return R.ok(signBo);
    }

    @Override
    public R rsignd(int rid) {
        List<ResidentSignDto> dto = dao.queryMoreInfo(rid);
        if (Objects.nonNull(dto)) {
            return R.ok(dto);
        } else {
            return R.fail("亲，查询异常！");
        }
    }

    @Override
    public R rsignlist(int rid) {
        List<ResidentSignDto> dtos = dao.queryMoreInfo(rid);
        List<ResidentSignListBo> boos = new ArrayList<>(dtos.size());
        if (dtos != null && dtos.size() > 0) {
            for (ResidentSignDto dto : dtos) {
                ResidentSignListBo bo = new ResidentSignListBo();
                BeanUtils.copyProperties(dto, bo);
                Calendar cal = Calendar.getInstance();
                cal.setTime(bo.getApplyTime());
                cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + dto.getPeriod());
                bo.setExpireTime(cal.getTime());
                boos.add(bo);
            }
            return R.ok(boos);
        } else {
            return R.ok();
        }
    }
}
